package com.trust.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.trust.agri.util.BeanUtil;
import com.trust.entity.SystemDepartment;
import com.trust.entity.VO.DeptListVO;
import com.trust.mapper.SystemDepartmentMapper;
import com.trust.service.SystemDepartmentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class SystemDepartmentServiceImpl extends ServiceImpl<SystemDepartmentMapper, SystemDepartment> implements SystemDepartmentService {


    @Override
    public String getNameById(Integer id) {
        SystemDepartment department = this.getById(id);
        if (null == department){
            return "";
        }
        return department.getName();
    }

    @Override
    public List<DeptListVO> tree(Integer parentId) {
        LambdaQueryWrapper<SystemDepartment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SystemDepartment::getParentId, null == parentId ? 0 : parentId);
        List<SystemDepartment> list = this.list(wrapper);
        if (CollectionUtil.isEmpty(list)){
            return new ArrayList<>();
        }
        List<DeptListVO> targetList = BeanUtil.sourceList2targetList(list, DeptListVO.class);
        for (DeptListVO vo : targetList) {
            this.getChildren(vo);
        }
        return targetList;
    }


    private void getChildren(DeptListVO vo){
        LambdaQueryWrapper<SystemDepartment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SystemDepartment::getParentId, vo.getId());
        List<SystemDepartment> list = this.list(wrapper);
        List<DeptListVO> targetList = BeanUtil.sourceList2targetList(list, DeptListVO.class);
        if (CollectionUtil.isNotEmpty(targetList)){
            for (DeptListVO deptListVO : targetList) {
                getChildren(deptListVO);
            }
            vo.setChildren(targetList);
        } else {
            vo.setChildren(targetList);
        }
    }
}
